package com.fs.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.fs.mapper.CaptMapper;
import com.fs.pojo.Capt;
import com.fs.pojo.EmailCapt;
import com.fs.pojo.User;
import com.fs.service.EmailCaptService;
import com.fs.service.EmailService;
import com.fs.service.UserService;
import com.fs.vo.RegisterSendEmailVO;
import com.fs.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username:abc}")
    private String emailUsername;

    @Value("${zj.user.register.email.title:注册成功}")
    private String emailTitle;

    @Value("${zj.user.register.email.content:注册成功}")
    private String emailContent;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private Producer producer;

    @Autowired
    private EmailCaptService emailCaptService;

    @Autowired
    private UserService userService;

    @Transactional
    @Override
    public ResultVO sendRegisterEmail(String email,Integer type) {

        if (StrUtil.isBlank(email)) return ResultVO.fail("邮件不能为空");
        String emailRegex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
        if (!email.matches(emailRegex)) return ResultVO.fail("邮箱格式不正确");

        String code = producer.createText();
        String content = emailContent;
        content = content.replace("--CODE--", code);

        Date now = new Date();

        //查找邮件是否已注册
        User userEntity = new User().setEmail(email);
        User one = userService.getOne(new QueryWrapper(userEntity));
        if (one != null) {
            return ResultVO.fail("此邮箱已注册");
        }

        //查找邮件验证码是否还在有效期
        QueryWrapper<EmailCapt> wrapper = new QueryWrapper();
        wrapper.eq("email", email)
                .eq("status", false)
                .eq("type",type)
                .gt("expire_time",now)
                .orderByDesc("expire_time");
        EmailCapt one1 = emailCaptService.getOne(wrapper);
        if(one1 != null ){
            return ResultVO.fail("5分钟后再试");
        }


        try {
            // 构建一个邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件主题
            message.setSubject(emailTitle);
            // 设置邮件发送者，这个跟application.yml中设置的要一致
            message.setFrom(emailUsername);
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
            // message.setTo("","");
            message.setTo(email);
            // 设置邮件抄送人，可以有多个抄送人
//        message.setCc("");
            // 设置隐秘抄送人，可以有多个
//        message.setBcc("");
            // 设置邮件发送日期
            message.setSentDate(now);
            // 设置邮件的正文
            message.setText(content);
            // 发送邮件
            javaMailSender.send(message);

            String uuid = UUID.randomUUID().toString();

            //5分钟后过期
            Date date = new Date();
            EmailCapt entity = new EmailCapt(uuid, code, DateUtil.offsetMinute(date, 5), email, false,type);

            emailCaptService.save(entity);

            return ResultVO.success();
        } catch (MailException e) {
            return ResultVO.fail("邮件发送失败");
        }
    }

    @Override
    public ResultVO sendForgetEmail(String email, int i) {
        if (StrUtil.isBlank(email)) return ResultVO.fail("邮件不能为空");
        String emailRegex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
        if (!email.matches(emailRegex)) return ResultVO.fail("邮箱格式不正确");

        String code = producer.createText();
        String content = emailContent;
        content = content.replace("--CODE--", code);

        Date now = new Date();

        //查找邮件是否已注册
        User userEntity = new User().setEmail(email);
//        UserEntity one = userService.getOne(new QueryWrapper<>(userEntity));
        List<User> userList = userService.list((new QueryWrapper(userEntity)));

        if (userList == null) {
            return ResultVO.fail("此邮箱未注册");
        }

        if(userList.size()>1){
            return ResultVO.fail("此邮箱存在多个用户");
        }

        //查找邮件验证码是否还在有效期
        QueryWrapper<EmailCapt> wrapper = new QueryWrapper();
        wrapper.eq("email", email)
                .eq("status", false)
                .eq("type",i)
                .gt("expire_time",now)
                .orderByDesc("expire_time");
        EmailCapt one1 = emailCaptService.getOne(wrapper);
        if(one1 != null ){
            return ResultVO.fail("5分钟后再试");
        }


        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(emailTitle);
            message.setFrom(emailUsername);
            message.setTo(email);
            message.setSentDate(now);
            message.setText(content);
            javaMailSender.send(message);

            String uuid = UUID.randomUUID().toString();

            //5分钟后过期
            Date date = new Date();
            EmailCapt entity = new EmailCapt(uuid, code, DateUtil.offsetMinute(date, 5), email, false,i);

            emailCaptService.save(entity);

            return ResultVO.success();
        } catch (MailException e) {
            return ResultVO.fail("邮件发送失败");
        }
    }
}
